package com.boyuan.huijiaoyu;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.example.app.Url;
import com.example.contactfragment.ContactGroupService;
import com.example.contactfragment.ContactService;
import com.example.huanxin.more.DownLoad;
import com.example.newfragment.DetailPerson;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.constant.Constant;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MyFriendActivity extends Activity implements OnClickListener {

	private ListView listview;
	private ContactService contactService;
	private ContactGroupService contactgroupService;
	String id;
	private ArrayList<DetailPerson> friendlist = new ArrayList<DetailPerson>();
	private ArrayList<String> userlist = new ArrayList<String>();
	private ArrayList<String> usernamelist = new ArrayList<String>();
	private ArrayList<String> addlist = new ArrayList<String>();
	private ArrayList<String> mobilelist = new ArrayList<String>();
	private ArrayList<String> uidlist = new ArrayList<String>();
	private ArrayList<String> namelist = new ArrayList<String>();
	private MyAdapter adapter;
	boolean isrequestok = false;
	boolean isgetcontactdatil;
	String accounts[];
	private String groupid;
	ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	HashMap<String, Bitmap> photos = new HashMap<String, Bitmap>();
	private ArrayList<String> urllist = new ArrayList<String>();
	
	private int count=0;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			int result =msg.what;
			count+=result;
			if(count==3){
				Toast.makeText(MyFriendActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
			}
		};
	};
	private RelativeLayout layok;
	private TextView tvok;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_friend);
		Intent intent = getIntent();
		userlist = intent.getStringArrayListExtra("phonelist");
		usernamelist = intent.getStringArrayListExtra("usernamelist");
		groupid = intent.getStringExtra("groupid");
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		id = sp.getString("id", "");
		getMyFriendCache();
//		getFrequentContacts();
		initUI();
	}

	private void initUI() {
		findViewById(R.id.lay_back).setOnClickListener(this);
		layok = (RelativeLayout) findViewById(R.id.lay_save);
		layok.setOnClickListener(this);
		tvok = (TextView) findViewById(R.id.tv_addfriend);
		listview = (ListView) findViewById(R.id.listView11);
		adapter = new MyAdapter();
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
					CheckBox cb1 = (CheckBox) view.findViewById(R.id.checkBox1);
					cb1.toggle();
			}
		});
		
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
//			return mobilelist.size();
			return namelist.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			View inflate = getLayoutInflater().inflate(R.layout.list_friend,
					null);
			final CheckBox cb = (CheckBox) inflate.findViewById(R.id.checkBox1);
			final TextView tv = (TextView) inflate.findViewById(R.id.tvname);
			ImageView photo1 = (ImageView) inflate.findViewById(R.id.imag_photo);
			tv.setText(namelist.get(arg0));
			options = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.default_header)
			.showImageForEmptyUri(R.drawable.default_header)
			.showImageOnFail(R.drawable.default_header).cacheInMemory(true)
			.cacheOnDisc(true).considerExifParams(true)
			.build();
//			String uri = Constant.photourl + mobilelist.get(arg0);
			String uri = Constant.photourl + uidlist.get(arg0);
			imageLoader.displayImage(uri, photo1);
//			Bitmap bitmap = photos.get(uri);
//			if(bitmap == null){
//				ImageAsyncTask imageAsyncTask = new ImageAsyncTask(photo1);
//				imageAsyncTask.execute(uri);
//			}else{
//				photo1.setImageBitmap(bitmap);
//			}
			
//			//下载头像到sd卡
//			new Thread(){
//				@Override
//				public void run() {
//					for(int i=0;i<urllist.size();i++){
//						DownLoad downLoad=new DownLoad(handler);
//						downLoad.downLoadFile(urllist.get(i));
//					}
//				}
//			}.start();
			
			if (usernamelist.contains(tv.getText().toString().trim())) {
				cb.setChecked(true);
			}
	
			cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton compoundButton,
						boolean ischecked) {
					if (usernamelist.contains(tv.getText().toString().trim())) {
						ischecked = true;
						cb.setChecked(true);
					}
					if (ischecked) {
						if (usernamelist.contains(tv.getText().toString().trim())) {
							// Toast.makeText(MyFriendActivity.this, "已在群里",
							// Toast.LENGTH_LONG).show();
						} else {
							addlist.add(mobilelist.get(arg0));
							if(addlist.size()>0){
								layok.setBackgroundColor(Color.parseColor("#3DB516"));
								tvok.setText("确定("+addlist.size()+")");
							}else{
								layok.setBackgroundColor(Color.parseColor("#256816"));
								tvok.setText("确定");
							}
						}
					} else {
						if (usernamelist.contains(tv.getText().toString().trim())) {

						} else {
							addlist.remove(mobilelist.get(arg0));
							if(addlist.size()>0){
								layok.setBackgroundColor(Color.parseColor("#3DB516"));
								tvok.setText("确定("+addlist.size()+")");
							}else{
								layok.setBackgroundColor(Color.parseColor("#256816"));
								tvok.setText("确定");
							}
						}
					}
					
				}
			});

			return inflate;
		}

	}
	
//	//异步加载图片
//	class ImageAsyncTask extends AsyncTask<String, Void, Bitmap>{
//		
//		ImageView image;
//		public ImageAsyncTask(ImageView image){
//			this.image = image;
//		}
//
//		@Override
//		protected Bitmap doInBackground(String... params) {
//			Bitmap bitmap = null;
//			String path = params[0];
//			try {
//				URL url = new URL(path);
//				URLConnection openConnection = url.openConnection();
//				InputStream inputStream = openConnection.getInputStream();
//				bitmap = BitmapFactory.decodeStream(inputStream);
//				FileOutputStream fos = new FileOutputStream(path);
//				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//				photos.put(path, bitmap);
//			} catch (MalformedURLException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//			return bitmap;
//		}
//		
//		@Override
//		protected void onPostExecute(Bitmap result) {
//			image.setImageBitmap(result);
//			super.onPostExecute(result);
//		}
//		
//	}
	
	//获取我的好友缓存
			private void getMyFriendCache() {
				friendlist.clear();
				mobilelist.clear();
				uidlist.clear();
				namelist.clear();
				urllist.clear();
				ArrayList<DetailPerson> myfriendList = SharePreferenceHelper.getContactFrindList(MyFriendActivity.this, id);
				if (myfriendList.size() > 0) {
					friendlist.addAll(myfriendList);
					for (int i = 0; i < friendlist.size(); i++) {
						mobilelist.add(friendlist.get(i).getMobile());
						uidlist.add(friendlist.get(i).getUid());
						namelist.add(friendlist.get(i).getRealname());
						urllist.add(Constant.photourl + friendlist.get(i).getMobile());
					}
				}else{
					Toast.makeText(MyFriendActivity.this, "您还没有好友！", Toast.LENGTH_SHORT).show();
					finish();
				}
			}
	

	/**
	 * 获取常用联系人
	 */
	private void getFrequentContacts() {

		if (contactService == null) {
			contactService = new ContactService(this);
		}
		contactService.getFrequentContacts(id,
				new GetOneRecordListener<List<DetailPerson>>() {

					@Override
					public void onFinish(List<DetailPerson> data) {
						friendlist.clear();
						mobilelist.clear();
						namelist.clear();
						urllist.clear();
						if (data != null && data.size() > 0) {
							friendlist.addAll(data);
							SharePreferenceHelper.saveMyFrindList(MyFriendActivity.this, id, data);
							for (int i = 0; i < friendlist.size(); i++) {
								mobilelist.add(friendlist.get(i).getMobile());
								namelist.add(friendlist.get(i).getRealname());
								urllist.add(Constant.photourl + friendlist.get(i).getMobile());
							}
							isrequestok = true;

						} else {
							Toast.makeText(MyFriendActivity.this, "您还没有好友！",
									Toast.LENGTH_SHORT).show();
							finish();
						}
						adapter.notifyDataSetChanged();
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(MyFriendActivity.this, Message,
								false);
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.my_friend, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.lay_back:
			finish();
			break;
		case R.id.lay_save:
			if(addlist.size()>0){
				addMenbersToGroup();
			}else{
				Toast.makeText(MyFriendActivity.this, "请选择要添加的好友！",Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
	}

	public void addMenbersToGroup() {
		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(this);
		}
		StringBuffer sb = new StringBuffer();
		String usernames = "";
		for (int i = 0; i < addlist.size(); i++) {
			sb.append(addlist.get(i) + ",");
		}
		if(sb.length()>0){
			usernames = sb.substring(0, sb.length() - 1);
		}
		contactgroupService.addcontacts(groupid, usernames,
				new GetMultilParamsListener() {

					@Override
					public void onFinish(Object... params) {
						if (params != null) {
							// GroupAddMember group = (GroupAddMember)
							// params[0];
							Intent intent = new Intent();
							setResult(2, intent);
							finish();
						}

					}

					@Override
					public void onFailed(String Message) {
					}
				});
	}

}
